package com.ysstech.common.realm;

import java.lang.annotation.Annotation;

import com.ysstech.common.annotation.YssPermissions;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler;
import org.apache.shiro.subject.Subject;

/**
 * 自定义的权限认证方法 @YssPermissions
 */
@Slf4j
public class YssAuthorizingAnnotationHandler extends AuthorizingAnnotationHandler {
    // 继承父类构造器，注入SalmonRequiresPermissions注解
    public YssAuthorizingAnnotationHandler() {
        super(YssPermissions.class);
    }


    public void assertAuthorized(Annotation a) {
        try {
            if (a instanceof YssPermissions) {
                Subject subject = this.getSubject();
                YssPermissions rpAnnotation = (YssPermissions) a;
                String[] permissions = rpAnnotation.value();
                if (permissions.length == 1) {
                    subject.checkPermission(permissions[0]);
                    return;
                }
                if (Logical.AND.equals(rpAnnotation.logical())) {
                    this.getSubject().checkPermissions(permissions);
                    return;
                }
                if (Logical.OR.equals(rpAnnotation.logical())) {
                    boolean hasAtLeastOnePermission = false;
                    String[] perArr = permissions;
                    for (String per : perArr) {
                        if (this.getSubject().isPermitted(per)) {
                            hasAtLeastOnePermission = true;
                        }
                    }
                    if (!hasAtLeastOnePermission) {
                        this.getSubject().checkPermission(permissions[0]);
                    }
                    return;
                }
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new UnauthorizedException("检查权限出错！");
        }
    }
}
